package com.itheima.filter;

import com.itheima.common.GetThreadLocal;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * @Description: 改过滤器只判断用户是否登录，登录之后将session中获取到的id存到ThradLocal中。
 * @Create by: JJ菜菜
 * @Date: 2021/11/1 18:32
 */
@WebFilter("/*")
//@Order(1)
public class GetIdToSession implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        Long id = (Long) session.getAttribute("employee");
        if(id != null){
            // 已经登录
            // 将session中的id存储到ThreadLocal中。
            GetThreadLocal.setThreadLocal(id);
            // 放行
        }

        Long userId = (Long) session.getAttribute("user");
        if(userId != null){
            // 如果已经登录就将userId存到ThreadLocal中
            GetThreadLocal.setThreadLocal(userId);
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
